package com.example.lj.uav.adapter;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.lj.uav.R;
import com.example.lj.uav.holder.FileHolder;

import java.io.File;

public class FileAdapter extends RecyclerView.Adapter<FileHolder> {
    private File[] fileList;
    private Context context;
    private Handler mHandler;

    public static final int FILE_FOLDER_SELECTED = 20;
    public static final int FILE_SELECTED = 21;

    public FileAdapter(File[] fileList,Context context,Handler handler) {
        this.fileList = fileList;
        this.context = context;
        mHandler = handler;
    }

    @Override
    public FileHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_file_list,null);
        return new FileHolder(view);
    }

    @Override
    public void onBindViewHolder(FileHolder holder, final int position) {

        if (fileList[position].getName().endsWith(".kml")){
            holder.mIv.setImageBitmap(BitmapFactory.decodeResource(context.getResources(),R.drawable.file));
        }else if (fileList[position].isDirectory()){
            holder.mIv.setImageBitmap(BitmapFactory.decodeResource(context.getResources(),R.drawable.file_folder));
        }
        String name = fileList[position].getName();
        holder.tv_file_name.setText(name);
        final String path = fileList[position].getPath();
        holder.tv_file_path.setText(path);
        holder.ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = fileList[position];
                Message message = mHandler.obtainMessage();
                if (file.isDirectory()){
                    message.what = FILE_FOLDER_SELECTED;
                    message.arg1 = position;
                    mHandler.sendMessage(message);
                }else{
                    message.what = FILE_SELECTED;
                    message.arg1 = position;
                    mHandler.sendMessage(message);
                }

            }
        });
    }

    @Override
    public int getItemCount() {
        return fileList.length;
    }
}
